const API_KEY = 'sk-vBvwY4XmFjV6HGzeFuJmWoMARPiNBL2M';
const API_URL = 'https://api.sensenova.cn/compatible-mode/v1/chat/completions';
let chatHistory = [];

// 在文件开头添加
console.time('页面总加载时间');
window.addEventListener('load', () => {
    console.timeEnd('页面总加载时间');
});

// 添加全局变量存储科室数据
let availableDepartments = [];

// 页面加载时初始化
// 修改 window.onload 中的系统提示部分
window.onload = function() {
    const welcomeMessage = "您好！请描述您的症状或想要就诊的科室，我会尽力为您提供专业的建议。";
    appendMessage('bot', welcomeMessage, 'DeepSeek', getCurrentTime());
    
    // 从ks.json加载科室数据
    fetch('ks.json')
        .then(response => response.json())
        .then(data => {
            availableDepartments = data.hospital.departments;
            console.log('科室数据加载成功，共', availableDepartments.length, '个科室');
            
            const deptNames = availableDepartments.map(d => d.name).join('、');
            const systemPrompt = `你是一个专业的医疗助手。可选科室列表：${deptNames}。诊断流程：
            1. 首先评估症状与科室的匹配度
            2. 如果最佳匹配科室的匹配度低于80%：
               - 不要给出任何科室建议
               - 提出1-2个关键问题，帮助进一步明确诊断科室
               - 在问题之前说明"为了更准确地为您推荐科室，请告诉我："
            3. 如果存在匹配度达到80%或以上的科室：
               - 使用固定格式推荐：推荐就诊科室：1.XX科（匹配度：XX%）。2.XX科（匹配度：XX%）。3.XX科（匹配度：XX%）
            4. 如果用户指定某个科室：
               - 通过追问确认症状是否匹配该科室
               - 仅在匹配度达到80%时推荐该科室`;
            
            chatHistory.push({
                role: 'system',
                content: systemPrompt
            });
        })
        .catch(error => {
            console.error('获取科室列表失败:', error);
            chatHistory.push({
                role: 'system',
                content: '你是一个专业的医疗助手，请根据用户描述的症状提供专业的健康建议，但要强调这只是初步建议，不能替代医生的诊断。'
            });
        })
        .finally(() => {
            chatHistory.push({
                role: 'assistant',
                content: welcomeMessage
            });
            

        });
}

// 修改 standardizeDepartmentName 函数，使用预加载的科室数据
function standardizeDepartmentName(name) {
    // 去除可能的前缀和后缀
    let deptName = name.replace(/^到|^去|^前往|^就诊|^咨询|^挂号|医院的/, '').trim();
    
    // 确保科室名称以"科"结尾
    if (!deptName.endsWith('科') && !deptName.endsWith('诊') && !deptName.endsWith('中心')) {
        deptName += '科';
    }
    
    // 使用预加载的科室数据进行匹配
    if (availableDepartments && availableDepartments.length > 0) {
        // 完全匹配
        const exactMatch = availableDepartments.find(d => d.name === deptName);
        if (exactMatch) return exactMatch.name;
        
        // 不带"科"字的匹配
        const nameWithoutSuffix = deptName.replace(/科$/, '').replace(/中心$/, '');
        const matchWithoutSuffix = availableDepartments.find(d => 
            d.name.replace(/科$/, '').replace(/中心$/, '') === nameWithoutSuffix);
        if (matchWithoutSuffix) return matchWithoutSuffix.name;
    }
    
    return null; // 如果没有匹配的科室，返回null
}



// 添加 useQuickQuestion 函数定义
function useQuickQuestion(question) {
    document.getElementById('userInput').value = question;
    sendMessage();
}

function getCurrentTime() {
    const now = new Date();
    return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
}

// 在 sendMessage 函数开头添加
async function sendMessage() {
    console.time('消息处理时间');
    const userInput = document.getElementById('userInput');
    const message = userInput.value.trim();
    if (!message) return;

    appendMessage('user', message, '我', getCurrentTime());
    userInput.value = '';
    
    chatHistory.push({
        role: 'user',
        content: message
    });

    const typingIndicator = document.createElement('div');
    typingIndicator.className = 'typing-indicator';
    typingIndicator.innerHTML = `
        <div class="avatar"><i class="fas fa-user-md"></i></div>
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
    `;
    document.getElementById('chatContainer').appendChild(typingIndicator);
    document.getElementById('chatContainer').scrollTop = document.getElementById('chatContainer').scrollHeight;

    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`,
                'Accept': 'text/event-stream',
                'Connection': 'keep-alive'
            },
            body: JSON.stringify({
                model: 'DeepSeek-V3',
                messages: chatHistory,
                stream: true,
                temperature: 0.7,
                max_tokens: 2048
            })
        });

        if (!response.ok) {
            const errorData = await response.text();
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorData}`);
        }

        typingIndicator.remove();
        const messageElement = appendMessage('bot', '', 'DeepSeek', getCurrentTime());
        const reader = response.body.getReader();
        let decoder = new TextDecoder();
        let fullResponse = '';

        function readStream() {
            reader.read().then(({ done, value }) => {
                if (done) {
                    // 流结束，响应完成
                    removeLoadingMessage(loadingMessageId);
                    
                    // 在这里调用onApiResponseComplete
                    onApiResponseComplete(fullResponse);
                    return;
                }
                
                // 处理接收到的数据
                const chunk = decoder.decode(value, { stream: true });
                // 处理chunk...
                fullResponse += processedText; // 假设processedText是处理后的文本
                
                // 继续读取
                readStream();
            });
        }

        readStream();
        // 处理流式响应
        try {
            let fullResponse = '';
            
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const text = new TextDecoder().decode(value);
                const chunks = text.split('\n').filter(chunk => chunk.trim());

                for (const chunk of chunks) {
                    if (!chunk.startsWith('data:')) continue;
                    if (chunk.includes('[DONE]')) continue;

                    try {
                        const json = JSON.parse(chunk.replace('data:', '').trim());
                        const content = json.choices[0]?.delta?.content;
                        if (content) {
                            fullResponse += content;
                            messageElement.querySelector('.message-content').innerHTML = formatMessage(fullResponse);
                            chatContainer.scrollTop = chatContainer.scrollHeight;
                        }
                    } catch (e) {
                        console.error('JSON解析错误:', e);
                    }
                }
            }
            
            chatHistory.push({
                role: 'assistant',
                content: fullResponse
            });
            
            // 调用onApiResponseComplete函数更新快速提问
            onApiResponseComplete(fullResponse);
            
            // 确保在这里调用科室推荐函数，并添加日志
            console.log('准备推荐科室，AI回复长度:', fullResponse.length);
            recommendDepartment(message, fullResponse);
            
        } catch (e) {
            console.error('流读取错误:', e);
        } finally {
            reader.releaseLock();
        }
    } catch (error) {
        if (typingIndicator) typingIndicator.remove();
        appendMessage('bot', `抱歉，出现了错误：${error.message}`, '智能医疗助手', getCurrentTime());
    }
    
    console.timeEnd('消息处理时间');
}

function appendMessage(role, content, sender, time) {
    const chatContainer = document.getElementById('chatContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;
    
    const messageHeader = document.createElement('div');
    messageHeader.className = 'message-header';
    
    const avatar = document.createElement('div');
    avatar.className = `avatar ${role === 'bot' ? 'bot-avatar' : 'user-avatar'}`;
    avatar.innerHTML = role === 'bot' ? '<i class="fas fa-user-md"></i>' : '<i class="fas fa-user"></i>';
    
    const senderName = document.createElement('div');
    senderName.className = 'sender-name';
    senderName.textContent = sender;
    
    const messageTime = document.createElement('div');
    messageTime.className = 'message-time';
    messageTime.textContent = time;
    
    messageHeader.appendChild(avatar);
    messageHeader.appendChild(senderName);
    messageHeader.appendChild(messageTime);
    
    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';
    messageContent.innerHTML = formatMessage(content);
    
    messageDiv.appendChild(messageHeader);
    messageDiv.appendChild(messageContent);
    
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
    return messageDiv;
}

function formatMessage(content) {
    if (!content) return '';
    
    let formatted = content;
    
    formatted = formatted.replace(/^(#{1,6})\s+(.+)$/gm, function(match, hashes, text) {
        const level = hashes.length;
        return `<h${level} style="margin: 10px 0; color: var(--primary-color);">${text}</h${level}>`;
    });
    
    formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
    formatted = formatted.replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>');
    formatted = formatted.replace(/(<li>.*<\/li>(\n|$))+/g, '<ol style="margin-left: 20px;">$&</ol>');
    formatted = formatted.replace(/^[\*\-]\s+(.+)$/gm, '<li>$1</li>');
    formatted = formatted.replace(/(<li>.*<\/li>(\n|$))+/g, '<ul style="margin-left: 20px;">$&</ul>');
    formatted = formatted.replace(/^>\s+(.+)$/gm, '<blockquote style="border-left: 3px solid var(--primary-color); padding-left: 10px; color: #666;">$1</blockquote>');
    formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto;"><code>$1</code></pre>');
    formatted = formatted.replace(/`([^`]+)`/g, '<code style="background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px;">$1</code>');
    formatted = formatted.replace(/^---+$/gm, '<hr style="border: 0; border-top: 1px solid #eee; margin: 10px 0;">');
    
    // 修改换行符处理逻辑
    formatted = formatted.replace(/\n{3,}/g, '<br>'); // 三个及以上换行转为一个换行
    formatted = formatted.replace(/\n\n/g, '<br>'); // 两个换行转为一个换行
    formatted = formatted.replace(/\n/g, ' '); // 单个换行转为空格
    
    // URL 和医学术语处理保持不变
    formatted = formatted.replace(
        /(https?:\/\/[^\s]+)/g, 
        '<a href="$1" target="_blank" style="color:var(--primary-color);text-decoration:underline;">$1</a>'
    );
    
    const medicalTerms = [
        '高血压', '糖尿病', '心脏病', '冠心病', '脑卒中', '肺炎', 
        '哮喘', '慢性阻塞性肺疾病', '肝炎', '肾炎', '胃炎', '溃疡', 
        '贫血', '白血病', '甲状腺', 'ndepartments', '焦虑症'
    ];
    
    medicalTerms.forEach(term => {
        const regex = new RegExp(`(${term})`, 'g');
        formatted = formatted.replace(regex, '<span style="color:var(--secondary-color);font-weight:bold;">$1</span>');
    });
    
    return formatted;
}

const departments = [
    { name: '内科', keywords: ['发热', '头痛', '咳嗽', '胸痛', '心悸', '呼吸困难', '腹痛', '腹泻', '便秘', '恶心', '呕吐', '乏力', '疲劳', '高血压', '糖尿病', '心脏病'] },
    { name: '外科', keywords: ['外伤', '骨折', '脱位', '扭伤', '烧伤', '烫伤', '切割伤', '肿块', '肿瘤', '疼痛', '手术'] },
    { name: '妇产科', keywords: ['月经', '痛经', '闭经', '不孕', '怀孕', '孕吐', '产前', '产后', '乳房', '宫颈', '子宫', '卵巢'] },
    { name: '儿科', keywords: ['婴儿', '幼儿', '儿童', '发育', '生长', '疫苗', '免疫', '小儿'] },
    { name: '眼科', keywords: ['视力', '眼睛', '眼痛', '眼红', '眼干', '眼花', '近视', '远视', '散光', '白内障', '青光眼'] },
    { name: '耳鼻喉科', keywords: ['耳朵', '耳痛', '耳鸣', '听力', '鼻子', '鼻塞', '流鼻血', '打喷嚏', '咽喉', '扁桃体', '嗓子'] },
    { name: '口腔科', keywords: ['牙痛', '蛀牙', '牙龈', '口腔', '口臭', '舌头', '牙齿', '牙龈炎', '牙周炎'] },
    { name: '皮肤科', keywords: ['皮疹', '瘙痒', '湿疹', '痤疮', '皮肤', '脱发', '斑点', '红斑', '过敏', '荨麻疹'] },
    { name: '神经内科', keywords: ['头晕', '头痛', '失眠', '抑郁', '焦虑', '记忆力', '晕厥', '癫痫', '中风', '脑卒中', '帕金森'] },
    { name: '精神科', keywords: ['ndepartments', '焦虑症', '强迫症', '精神分裂', '躁狂', '失眠', '心理', '精神', '情绪'] },
    { name: '骨科', keywords: ['骨折', '关节痛', '腰痛', '颈椎', '腰椎', '膝盖', '肩膀', '骨质疏松', '关节炎', '风湿'] },
    { name: '泌尿外科', keywords: ['尿频', '尿急', '尿痛', '尿血', '尿路', '肾脏', '膀胱', '前列腺', '结石'] },
    { name: '心胸外科', keywords: ['心脏', '胸痛', '心绞痛', '心肌梗塞', '冠心病', '心律不齐', '心脏瓣膜', '主动脉'] },
    { name: '肿瘤科', keywords: ['肿瘤', '癌症', '恶性', '良性', '化疗', '放疗', '肿块'] },
    { name: '内分泌科', keywords: ['甲状腺', '糖尿病', '肥胖', '代谢', '内分泌', '激素', '肾上腺'] },
    { name: '感染科', keywords: ['发热', '感染', '病毒', '细菌', '真菌', '寄生虫', '传染病', '艾滋病', '肝炎'] },
    { name: '急诊科', keywords: ['急性', '突发', '剧痛', '昏迷', '休克', '抢救', '意外', '事故'] }
];

// 在 recommendDepartment 函数中添加科室推荐逻辑
// 修改 recommendDepartment 函数中的正则表达式部分
function recommendDepartment(userMessage, aiResponse) {
    console.time('科室推荐处理时间');
    console.log('开始科室推荐处理，用户消息长度:', userMessage.length, '，AI回复长度:', aiResponse.length);
    
    try {
        // 1. 首先尝试从AI回复中提取推荐科室信息 - 修改正则表达式使其更灵活
        const recommendationPattern = /推荐就诊科室：\s*1\.\s*([^（]+)\s*（匹配度：\s*(\d+)%）\s*。?\s*2\.\s*([^（]+)\s*（匹配度：\s*(\d+)%）\s*。?\s*3\.\s*([^（]+)\s*（匹配度：\s*(\d+)%）/;
        const match = aiResponse.match(recommendationPattern);
        
        if (match) {
            console.log('从AI回复中提取到科室推荐:', match);
            // 从AI回复中提取的科室推荐，确保科室名称格式一致
            const extractedDepartments = [
                { 
                    name: standardizeDepartmentName(match[1].trim()), 
                    score: parseInt(match[2]), 
                    isExplicit: true,
                    originalName: match[1].trim()  // 保存原始名称用于调试
                },
                { 
                    name: standardizeDepartmentName(match[3].trim()), 
                    score: parseInt(match[4]), 
                    isExplicit: true,
                    originalName: match[3].trim()
                },
                { 
                    name: standardizeDepartmentName(match[5].trim()), 
                    score: parseInt(match[6]), 
                    isExplicit: true,
                    originalName: match[5].trim()
                }
            ];
            
            console.log('标准化后的科室推荐:', extractedDepartments);
            displayDepartmentRecommendation(extractedDepartments);
            console.timeEnd('科室推荐处理时间');
            return;
        } else {
            console.log('未从AI回复中提取到标准格式的科室推荐，尝试其他格式');
            
            // 尝试其他可能的格式
            const alternativePattern = /建议(?:您)?(?:去|到|前往|就诊|咨询|挂号)?([^，。！？,.!?]+?)(?:科|诊)/g;
            let altMatch;
            const explicitRecommendations = [];
            
            while ((altMatch = alternativePattern.exec(aiResponse)) !== null) {
                const deptName = standardizeDepartmentName(altMatch[1].trim());
                if (deptName && !explicitRecommendations.some(d => d.name === deptName)) {
                    explicitRecommendations.push({
                        name: deptName,
                        score: 90 - explicitRecommendations.length * 5, // 按出现顺序降低分数
                        isExplicit: true
                    });
                }
                
                if (explicitRecommendations.length >= 3) break;
            }
            
            if (explicitRecommendations.length > 0) {
                console.log('从文本中提取到的科室推荐:', explicitRecommendations);
                // 如果不足3个，使用关键词匹配补充
                if (explicitRecommendations.length < 3) {
                    // ... 使用现有的关键词匹配逻辑补充 ...
                }
                displayDepartmentRecommendation(explicitRecommendations);
                console.timeEnd('科室推荐处理时间');
                return;
            }
        }
        
        // 2. 如果AI回复中没有提取到推荐科室，使用原有逻辑
        const combinedText = userMessage + ' ' + aiResponse;
        let matchedDepartments = [];
        
        // 检查明确推荐
        const explicitRecommendation = checkExplicitRecommendation(aiResponse);
        if (explicitRecommendation.length > 0) {
            console.log('检测到明确的科室推荐:', explicitRecommendation);
            matchedDepartments = explicitRecommendation.map(deptName => {
                const dept = departments.find(d => d.name === deptName);
                if (dept) {
                    return {
                        name: dept.name,
                        score: 95, // 给予明确推荐的科室较高分数
                        matchedKeywords: ['明确推荐'],
                        isExplicit: true
                    };
                }
                return {
                    name: deptName,
                    score: 95,
                    matchedKeywords: ['明确推荐'],
                    isExplicit: true
                };
            });
        }
        
        // 关键词匹配
        const keywordMatchedDepts = [];
        departments.forEach(dept => {
            // 如果已经在明确推荐中，跳过
            if (matchedDepartments.some(d => d.name === dept.name)) {
                return;
            }
            
            let matchCount = 0;
            let totalKeywords = dept.keywords.length;
            let matchedKeywordsList = [];
            
            dept.keywords.forEach(keyword => {
                if (combinedText.includes(keyword)) {
                    matchCount++;
                    matchedKeywordsList.push(keyword);
                }
            });
            
            if (matchCount > 0) {
                // 计算匹配度百分比
                const matchPercentage = Math.min(Math.round((matchCount / totalKeywords) * 100), 90);
                
                keywordMatchedDepts.push({
                    name: dept.name,
                    score: matchPercentage,
                    matchedKeywords: matchedKeywordsList,
                    isExplicit: false
                });
            }
        });
        
        // 合并两种匹配结果
        matchedDepartments = [...matchedDepartments, ...keywordMatchedDepts];
        
        // 排序
        matchedDepartments.sort((a, b) => {
            if (a.isExplicit && !b.isExplicit) return -1;
            if (!a.isExplicit && b.isExplicit) return 1;
            return b.score - a.score;
        });
        
        // 取前三个
        const topDepartments = matchedDepartments.slice(0, 3);
        
        // 如果不足三个，补充常见科室
        while (topDepartments.length < 3) {
            const commonDepts = ['内科', '外科', '急诊科'];
            for (const deptName of commonDepts) {
                if (!topDepartments.some(d => d.name === deptName)) {
                    topDepartments.push({
                        name: deptName,
                        score: 30,
                        matchedKeywords: ['常见科室'],
                        isExplicit: false
                    });
                    break;
                }
            }
            // 防止无限循环
            if (topDepartments.length < 3) {
                topDepartments.push({
                    name: '综合门诊',
                    score: 25,
                    matchedKeywords: ['兜底科室'],
                    isExplicit: false
                });
            }
        }
        
        if (topDepartments.length > 0) {
            displayDepartmentRecommendation(topDepartments);
        }
        
        console.timeEnd('科室推荐处理时间');
    } catch (error) {
        console.error('科室推荐处理出错:', error);
        // 出错时使用默认科室
        const defaultDepartments = [
            { name: '内科', score: 50, isExplicit: false },
            { name: '外科', score: 40, isExplicit: false },
            { name: '急诊科', score: 30, isExplicit: false }
        ];
        displayDepartmentRecommendation(defaultDepartments);
    }
    
    console.timeEnd('科室推荐处理时间');
}

// 添加科室名称标准化函数
function standardizeDepartmentName(name) {
    // 去除可能的前缀和后缀
    let deptName = name.replace(/^到|^去|^前往|^就诊|^咨询|^挂号|医院的/, '').trim();
    
    // 确保科室名称以"科"结尾
    if (!deptName.endsWith('科') && !deptName.endsWith('诊') && !deptName.endsWith('中心')) {
        deptName += '科';
    }
    
    // 使用预加载的科室数据进行匹配
    if (availableDepartments && availableDepartments.length > 0) {
        // 完全匹配
        const exactMatch = availableDepartments.find(d => d.name === deptName);
        if (exactMatch) return exactMatch.name;
        
        // 不带"科"字的匹配
        const nameWithoutSuffix = deptName.replace(/科$/, '').replace(/中心$/, '');
        const matchWithoutSuffix = availableDepartments.find(d => 
            d.name.replace(/科$/, '').replace(/中心$/, '') === nameWithoutSuffix);
        if (matchWithoutSuffix) return matchWithoutSuffix.name;
    }
    
    return null; // 如果没有匹配的科室，返回null
}

// 修改显示科室推荐的函数，确保正确显示匹配度
function displayDepartmentRecommendation(departments) {
    try {
        console.log('显示科室推荐:', departments);
        const chatContainer = document.getElementById('chatContainer');
        if (!chatContainer) {
            console.error('找不到聊天容器元素');
            return;
        }
        
        const recommendDiv = document.createElement('div');
        recommendDiv.className = 'department-recommendation';
        recommendDiv.style.margin = '15px 0';
        recommendDiv.style.padding = '15px';
        recommendDiv.style.backgroundColor = '#f0f7ff';
        recommendDiv.style.borderRadius = 'var(--border-radius)';
        recommendDiv.style.borderLeft = '4px solid var(--primary-color)';
        
        let html = `
            <div style="font-weight: bold; margin-bottom: 10px; color: var(--primary-color);">
                <i class="fas fa-hospital-user"></i> 科室推荐
            </div>
            <div style="font-size: 0.9rem; margin-bottom: 10px;">
                根据您的描述，建议您可以考虑以下科室就诊：
            </div>
            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
        `;
        
        departments.forEach((dept, index) => {
            // 获取科室信息
            let deptInfo = null;
            try {
                if (window.hospitalService && typeof window.hospitalService.getDepartmentInfo === 'function') {
                    deptInfo = window.hospitalService.getDepartmentInfo(dept.name);
                    console.log(`获取科室信息 ${dept.name}:`, deptInfo);
                }
            } catch (e) {
                console.error('获取科室信息失败:', e);
            }
            
            // 确保匹配度是有效数字
            const matchPercentage = isNaN(dept.score) ? 50 : dept.score;
            const matchColor = matchPercentage > 80 ? '#4caf50' : 
                          matchPercentage > 60 ? '#2196f3' : 
                          matchPercentage > 40 ? '#ff9800' : '#f44336';
            
            html += `
                <div style="background-color: ${index === 0 ? 'var(--primary-color)' : '#e3f2fd'}; 
                            color: ${index === 0 ? 'white' : 'var(--primary-color)'};
                            padding: 12px; 
                            border-radius: 10px; 
                            flex: 1;
                            min-width: 250px;
                            max-width: 100%;">
                    <div style="font-weight: bold; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center;">
                        <span><i class="fas fa-stethoscope"></i> ${dept.name}</span>
                        <span style="background-color: ${index === 0 ? 'rgba(255,255,255,0.2)' : matchColor}; 
                                    color: ${index === 0 ? 'white' : 'white'};
                                    padding: 2px 8px;
                                    border-radius: 10px;
                                    font-size: 0.8rem;">
                                匹配度: ${matchPercentage}%
                            </span>
                        </div>
                        ${deptInfo ? `
                            <div style="font-size: 0.85rem; color: ${index === 0 ? '#fff' : '#666'}; margin-top: 5px;">
                                <div style="margin-bottom: 5px;">${deptInfo.description || '专业诊治相关疾病'}</div>
                                <div><i class="fas fa-phone"></i> 门诊电话：${deptInfo.outpatient_tel || '请咨询医院总台'}</div>
                                ${deptInfo.ward_tel && deptInfo.ward_tel !== '无' ? 
                                    `<div><i class="fas fa-bed"></i> 病房电话：${deptInfo.ward_tel}</div>` : 
                                    ''}
                            </div>
                        ` : '<div style="font-size: 0.85rem; margin-top: 5px;">专业诊治相关疾病</div>'}
                    </div>
                `;
        });
        
        html += `</div>`;
        recommendDiv.innerHTML = html;
        chatContainer.appendChild(recommendDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
        console.log('科室推荐卡片已添加到DOM');
    } catch (error) {
        console.error('显示科室推荐卡片时出错:', error);
    }
}

// 支持按 Enter 发送消息，按 Shift + Enter 换行
document.getElementById('userInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

// 在输入框获得焦点时添加提示文本
document.getElementById('userInput').addEventListener('focus', function() {
    this.setAttribute('placeholder', '按 Enter 发送消息，按 Shift + Enter 换行...');
});

// 在输入框失去焦点时恢复原始提示文本
document.getElementById('userInput').addEventListener('blur', function() {
    this.setAttribute('placeholder', '请描述您的症状或健康问题...');
});

// API状态管理
const ApiStatusManager = {
    // 状态配置
    STATUS_CONFIG: {
        checking: {
            class: 'status-loading',
            icon: 'fa-circle-notch fa-spin',
            text: '检测DeepSeek API...'
        },
        online: {
            class: 'status-success',
            icon: 'fa-check-circle',
            text: latency => `DeepSeek在线 (${latency}ms)`
        },
        slow: {
            class: 'status-warning',
            icon: 'fa-exclamation-triangle',
            text: latency => `DeepSeek响应慢 (${latency}ms)`
        },
        offline: {
            class: 'status-error',
            icon: 'fa-times-circle',
            text: errorCode => `DeepSeek离线 (错误: ${errorCode})`
        }
    },

    // 更新状态显示
    updateStatus(elementId, status, data) {
        const elements = {
            container: document.getElementById(elementId),
            icon: document.getElementById(`${elementId}Icon`),
            text: document.getElementById(`${elementId}Text`)
        };

        if (!Object.values(elements).every(Boolean)) return;

        const config = this.STATUS_CONFIG[status];
        if (!config) return;

        elements.container.className = `status-indicator ${config.class}`;
        elements.icon.className = `fas ${config.icon}`;
        elements.text.textContent = typeof config.text === 'function' ? config.text(data) : config.text;
        elements.container.style.display = 'inline-flex';
    },

    // 检查API状态
    async checkStatus() {
        this.updateStatus('apiStatus', 'checking');

        try {
            const result = await this.retryOperation(this.testApiConnection.bind(this));
            const latency = result.latency;
            const status = latency < 500 ? 'online' : 'slow';
            this.updateStatus('apiStatus', status, latency);
        } catch (error) {
            console.error('API状态检测失败:', error);
            const statusCode = error.message.match(/\d{3}/) || ['未知'];
            this.updateStatus('apiStatus', 'offline', statusCode[0]);
        }
    },

    // 测试API连接
    async testApiConnection() {
        const startTime = Date.now();
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            },
            body: JSON.stringify({
                model: 'DeepSeek-V3',
                messages: [{ role: 'user', content: '测试连接' }],
                max_tokens: 1
            })
        });

        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
        }

        return { latency: Date.now() - startTime };
    },

    // 重试操作
    async retryOperation(operation, maxRetries = 2, delay = 1000) {
        let lastError;

        for (let i = 0; i <= maxRetries; i++) {
            try {
                return await operation();
            } catch (error) {
                lastError = error;
                if (i < maxRetries) {
                    await new Promise(resolve => setTimeout(resolve, delay));
                }
            }
        }

        throw lastError;
    }
};

// 检测API状态和响应延迟
const checkApiStatus = () => ApiStatusManager.checkStatus();

// 页面加载完成后检查API状态
window.addEventListener('DOMContentLoaded', () => {
    // 延迟2秒检查API状态，避免与初始化冲突
    setTimeout(() => {
        checkApiStatus();
    }, 2000);
});

// 在现有代码中添加以下函数

// 更新快速提问区域
function updateQuickQuestions(lastResponse) {
    if (!lastResponse) return;
    
    generateFollowUpQuestions(lastResponse)
        .then(questions => {
            const container = document.getElementById('quickQuestionsContainer');
            if (!container) return;
            
            container.innerHTML = '';
            
            questions.forEach(question => {
                const shortQuestion = question.length > 25 ? question.substring(0, 22) + '...' : question;
                const questionElement = createQuestionElement(shortQuestion, question);
                container.appendChild(questionElement);
            });
        })
        .catch(error => {
            console.error('生成后续问题失败:', error);
        });
}

// 创建问题元素
function createQuestionElement(shortQuestion, fullQuestion) {
    const element = document.createElement('div');
    element.className = 'quick-question';
    element.setAttribute('role', 'button');
    element.setAttribute('tabindex', '0');
    element.setAttribute('aria-label', `快速提问：${shortQuestion}`);
    element.textContent = shortQuestion;
    element.onclick = () => useQuickQuestion(fullQuestion);
    return element;
}

// 生成后续问题
async function generateFollowUpQuestions(lastResponse) {
    const defaultQuestions = [
        '这种情况需要就医吗？',
        '有哪些常见的治疗方法？',
        '如何预防这种情况？',
        '有什么需要注意的生活习惯？'
    ];
    
    try {
        const prompt = `基于以下对话内容，生成4-6个用户可能想要进一步了解的问题，每个问题不超过25个字，不要编号，直接输出问题文本，每行一个问题：\n\n${lastResponse}`;
        
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            },
            body: JSON.stringify({
                model: 'DeepSeek-V3',
                messages: [{ role: 'user', content: prompt }],
                max_tokens: 500,
                temperature: 0.7
            })
        });
        
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        const questions = data.choices[0].message.content.trim()
            .split('\n')
            .map(q => q.trim())
            .filter(q => q && !/^\d+\./.test(q));
        
        return questions.length >= 4 ? questions.slice(0, 6) : defaultQuestions;
    } catch (error) {
        console.error('生成后续问题时出错:', error);
        return defaultQuestions;
    }
}

// 修改现有的处理API响应的函数，在完成响应后更新快速提问
// 在处理完AI响应的地方（通常是在处理流式响应的最后）添加：

// 在处理完AI响应后调用
function onApiResponseComplete(responseText) {
    // 将响应添加到聊天历史
    chatHistory.push({
        role: 'assistant',
        content: responseText
    });
    
    // 更新快速提问区域
    updateQuickQuestions(responseText);
}